<?php
/**
 * Description of myFacebook: Classe per realitzar la
 * communicació amb el facebook de forma segura
 *
 * @author Ferran Martin
 * @version 0.1
 */
class myFacebook {

    /* Configuracions:
     * --------------
     * $SecretKey: clau secreta per validar les comunicacions entre la web i myFacebook
     * $facebook_api_path: path a la API de facebook (sempre ha d'acavar amb "/")
     * $facebook_api_filname: nom de l'arxiu de la API de facebook
     * $facebook_app_id: id de l'aplicació de facebook
     * $facebook_app_secret: clau secreta de l'aplicacio de facebook
     */
    private $SecretKey = "";
    private $facebook_api_path = "libs/";
    private $facebook_api_filname = "facebook.php";
    private $facebook_app_id = "114464181917929";
    private $facebook_app_secret = "02ed325a4ac5ff4f1ee5441aaff903bb";

    private $myFb = null;
    private $mySession = null;
    private $myUserFb = null;

    private $aParamsAllowed = array(
        'name', 'first_name', 'last_name', 'pic_square', 'id'
    );

    public $myFb_errors = array();
    public $isLogged = false;
    
    public function __construct() {
        
            $this->myFb = new Facebook(array(
              'appId'  => $this->facebook_app_id,
              'secret' => $this->facebook_app_secret,
              'cookie' => true, // enable optional cookie support
            ));

            $this->mySession = $this->myFb->getSession();

            // Session based API call.
            if ($this->mySession) {
              try {
                $uid = $this->myFb->getUser();
                $this->myUserFb = $this->myFb->api('/me');
                if (isset($this->myUserFb)) $this->isLogged = true;
              } catch (FacebookApiException $e) {
                return false;
              }
            }
            else return false;
    }

      ////////////////////////////////
     ///        Consultores        //
    ////////////////////////////////

    public function getId() {
          if ($this->isLogged()) return $this->myUserFb["id"];
          else return false;
    }

    public function getName() {
         if ($this->isLogged()) return $this->myUserFb["name"];
         else {
             throw new DCGameException("getName: User no Logged In!", 2);
             return false;
         }
    }

    public function getInfoFb($param) {
        if ($this->isLogged()) {
            if (!empty($param)) {
                if (in_array($param, $this->aParamsAllowed)) return $this->myUserFb[$param];
                else {
                    throw new DCGameException("getInfoFb: Param denied!", 3);
                    return false;
                }
            }
            else {
                throw new DCGameException("getInfoFb: Empty param!", 4);
                return false;
            }
        }
        else {
            throw new DCGameException("getInfoFb: User no Logged In!", 2);
            return false;
        }
    }

    private function isLogged() {
        if ($this->isLogged) return true;
        else return false;
    }

    public function getListFriends() {
        if ($this->isLogged()) {
            $fql = 'SELECT uid, name, first_name, pic_square, online_presence FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='.$this->myUserFb["id"].') AND is_app_user = 1';
            $_aFriends = array();

            try{
                $_aFriends = $this->myFb->api(array(
                    'method' => 'fql.query',
                    'query' => $fql
                ));
            } catch(FacebookApiException $e) {
                throw new DCGameException("getListFriends: Error Inesperado de Facebook", 1, $e);
            }

            return $_aFriends;
        }
        else {
            throw new DCGameException("getListFriends: User no Logged In!", 2);
            return false;
        }
    }

   //TODO
    public function getListFriendsNoApp() {
        if ($this->isLogged()) {
            $fql = 'SELECT uid, name, email FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='.$this->myUserFb["id"].')';// AND is_app_user = 0';
            $_aFriends = array();

            try{
                $_aFriends = $this->myFb->api(array(
                    'method' => 'fql.query',
                    'query' => $fql
                ));
            } catch(FacebookApiException $e) {
                throw new DCGameException("getListFriendsNoApp: Error Inesperado de Facebook", 1, $e);
            }

            return $_aFriends;
        }
        else {
            throw new DCGameException("getListFriendsNoApp: User no Logged In!", 2);
            return false;
        }
    }

    public function getMyInfo() {
        if ($this->isLogged()) {
            $fql = 'SELECT uid, name, first_name, pic_square, online_presence FROM user WHERE uid = '. $this->myUserFb["id"];
            $_aFriends = array();

            try{
                $_aFriends = $this->myFb->api(array(
                    'method' => 'fql.query',
                    'query' => $fql
                ));
            } catch(FacebookApiException $e) {
                throw new DCGameException("getMyInfo: Error Inesperado de Facebook", 1, $e);
            }
            

            return $_aFriends;
        }
        else {
            throw new DCGameException("getMyInfo: User no Logged In!", 2);
            return false;
        }
    }


    public function getLikes() {
        return $this->myFb->api('/me/likes/');
    }

    //TODO: prova sampe
    public function getCheckins() {
        return $this->myFb->api('/me/checkins/');

    }

    /**
    * Solicita la pagina de auth del fb
    *
    * @access public
    * @return void
    */
    public function fbRequestLogin() {
       $loginUrl = $this->myFb->getLoginUrl(array("next"=>"http://apps.facebook.com/desafiochampions/"));
       echo "<script> top.location.href='{$loginUrl}'; </script>";
    }

      /////////////////////////////////
     ///        Modificadores       //
    /////////////////////////////////


    
      /////////////////////////
     ///        Altres      //
    /////////////////////////

    public function publica_resultat($res){
        if ($this->isLogged()) {
            if ($res == 1) $text = "ganado";
            else if ($res == 2) $text = "perdido";
            else $text = "empatado";

            try{
                $_status = $this->myFb->api(array(
                        'method'    => 'links.post',
                        'url'       => "http://www.desafiochampions.com",
                        'comment'   => 'ha '.$text.' un partido en DesafioChampions!',
                        'image'     => "templates/black/images/facebook/wall-img.jpg"
                ));
            } catch(FacebookApiException $e) {
                throw new DCGameException("publica_resultat: Error Inesperado de Facebook", 1, $e);
            }

        }
        else {
            throw new DCGameException("publica_resultat: User no Logged In!", 2);
            return false;
        }
    }   
}
?>
